package cn.ygh.bbo.system.sdk.shiro.filter;

import cn.ygh.bbo.framerwork.config.constant.WebConstant;
import cn.ygh.bbo.system.sdk.shiro.RedisSessionDao;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author ygh
 * @Desc 前后端分离 自定义认证Filter 跨域处理
 * @date 2019/11/3
 */
public class UserAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
//        Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
        if (WebConstant.OPTIONS.equals(((HttpServletRequest) request).getMethod().toUpperCase())) {
            return true;
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse res = (HttpServletResponse)response;
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        res.setCharacterEncoding("UTF-8");
        PrintWriter writer = res.getWriter();
        writer.write("请先登陆");
        writer.close();
        return false;
    }

}
